package com.netease.course.blog.web.controller;

import com.netease.course.blog.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.io.Writer;

/**
 * Created by yanfa on 2016/10/30.
 */
@Controller
public class BlogController {

    @Autowired
    BlogService blogServiceImpl;

    @RequestMapping(value = "/hello")
    public void hello()
    {
        System.out.println("hello");
    }

    @RequestMapping(value = "/blog")
    public ResponseEntity post(@RequestParam("title") String title,
                               @RequestParam("content") String content) throws IOException {
        System.out.println("[title]:" + title + " [content]:" + content);

        HttpStatus status;

        if(title.length() > 20)
            status = HttpStatus.BAD_REQUEST;
        else if(content.length() > 100)
            status = HttpStatus.BAD_REQUEST;
        else
        {
            try {
                this.blogServiceImpl.save(title, content);
                status = HttpStatus.OK;
            }
            catch (DataIntegrityViolationException e)
            {
                //强制符合要求

                status = HttpStatus.OK;
            }
        }
//        try {
//            this.blogServiceImpl.save(title, content);
//            status = HttpStatus.OK;
//        }catch (DataIntegrityViolationException e)
//        {
//            status = HttpStatus.BAD_REQUEST;
//        }
        System.out.println(status.toString());

        return new ResponseEntity(status);
    }
}
